package com.zzq.interceptor;

import com.alibaba.fastjson.JSON;
import com.zzq.mapper.UserMapper;
import com.zzq.utils.IResult;
import com.zzq.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SuperUserInterceptor implements HandlerInterceptor {
    @Autowired
    UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String headerToken = request.getHeader("token");
        Claims claims = JWTUtil.verifyToken(headerToken);
        int userId = Integer.parseInt(claims.get("jti").toString());
        if(userMapper.getById(userId).getIsSuperuser() == 0) {
            response.getWriter().write(JSON.toJSONString(IResult.error("这是管理员才能使用的接口")));
            return false;
        }
        return true;
    }
}
